package xyz.quanguanjia.masterboy;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import xyz.quanguanjia.masterboy.model.MBDAccountInfoModel;
import xyz.quanguanjia.masterboy.net.ApiService;

public class MBDHttpClient {
    private static final String BASE_URL = "https://api.quanguanjia.xyz/";
    private static MBDHttpClient instance;

    public static final String TAG = "HttpRequestClientTAG";

    private MBDHttpClient() {
    }

    public static synchronized MBDHttpClient shared() {
        if (instance == null) {
            instance = new MBDHttpClient();
        }
        return instance;
    }

    private Retrofit getClient() {
        Retrofit retrofit = null;
        //鉴权
        if (MBDUserCenter.shared().getToken().length() > 0) {

            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(new HeaderInterceptor("Authorization", "Bearer " + MBDUserCenter.shared().getToken()))
                    .build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL).client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        } else {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL).client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }


    public HttpLoggingInterceptor loggingInterceptor() {
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.d(TAG, message);
            }
        });
        loggingInterceptor.setLevel(level);
        return loggingInterceptor;
    }

    public interface Callback {
        public void completion(boolean success, Error error, MBDModelResponse response);
    }

    public void doRequest(ServiceType type, HashMap<String, String> params, Callback callback) {
        ApiService apiService = this.getClient().create(ApiService.class);

        ServiceMedicator medicator = new ServiceMedicator(apiService);
        Call<MBDModelResponse> callb = medicator.apiServiceWith(type, params);

        callb.enqueue(new retrofit2.Callback<MBDModelResponse>() {
            @Override
            public void onResponse(Call<MBDModelResponse> call, Response<MBDModelResponse> response) {
                if (response.isSuccessful()) {
                    MBDModelResponse detail = response.body();
                    assert callback != null;
                    handleResponse(detail, callback);
                    if (null != detail.data)
                        System.out.println("网络请求返回结果" + detail.data.toString());
                } else {
                    // 处理错误的响应
                    if (callback != null) {
                        callback.completion(false, null, null);
                    }
                }
            }

            @Override
            public void onFailure(Call<MBDModelResponse> call, Throwable t) {
                // 处理错误的响应
                if (callback != null) {
                    callback.completion(false, null, null);
                }
            }
        });
    }

    public void doPostFileRequest(String filePath, HashMap<String, RequestBody> params, Callback callback) {
        List<File> fileList = new ArrayList<>();
        fileList.add(new File(filePath));
        List<MultipartBody.Part> partList = filesToMultipartBodyParts(fileList);
        ApiService apiService = this.getClient().create(ApiService.class);
        ServiceMedicator medicator = new ServiceMedicator(apiService);
        Call<MBDModelResponse> callb = medicator.doUploadFile(params, partList);
        callb.enqueue(new retrofit2.Callback<MBDModelResponse>() {
            @Override
            public void onResponse(Call<MBDModelResponse> call, Response<MBDModelResponse> response) {
                if (response.isSuccessful()) {
                    MBDModelResponse detail = response.body();
                    assert callback != null;
                    handleResponse(detail, callback);
                } else {
                    // 处理错误的响应
                    if (callback != null) {
                        String errMsg = "出现了错误" + response.errorBody().toString();
                        String msg = TextUtils.isEmpty(response.message()) ? errMsg : response.message();
                        Error error = new Error(msg);
                        callback.completion(false, error, null);
                    }
                }
            }

            @Override
            public void onFailure(Call<MBDModelResponse> call, Throwable t) {
                // 处理错误的响应
                if (callback != null) {
                    callback.completion(false, null, null);
                }
            }
        });
    }

    private void handleResponse(MBDModelResponse detail, Callback callback) {
        if (null != detail && !TextUtils.isEmpty(detail.code)) {
            if (detail.code.equals("200")) {
                callback.completion(true, null, detail);
            } else if (detail.code.equals("401")) {
                MBDUserCenter.shared().setToken("");
                MBDAccountInfoModel.clear();

                Error error = new Error("请重新登录");

                Toast.makeText(MBDApplication.getContext(), "请重新登录", Toast.LENGTH_LONG).show();

                MBDUserCenter.shared().setToken("");
                MBDAccountInfoModel.clear();

                Intent intent = new Intent(MBDNotificationCenter.NOTIFICATION_UPDATE_USERINFO);
                // 发送广播
                LocalBroadcastManager.getInstance(MBDApplication.getContext()).sendBroadcast(intent);

                callback.completion(false, error, null);
            } else if (detail.code.equals("500")) {
                Error error = new Error(detail.msg);
                callback.completion(false, error, null);
            }
        } else {
            Error error = null == detail ? new Error("数据为空！") : null;
            callback.completion(null != detail, error, detail);
        }

    }

    private List<MultipartBody.Part> filesToMultipartBodyParts(List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        for (File file : files) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }


}

